<template>
  <div class="app-container">
         <el-form :model="querys" ref="Form" :inline="true"  label-width="90px">
        <el-form-item label="日期类型：" prop="type">
          <el-radio-group
              v-model="radioTimeChange"
              @change="changeTab"
            >
              <el-radio  v-for="dict in dateTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" ></el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item :label="timeLable" prop="type">
          <el-date-picker
             v-if="type=='1'"
             v-model="value1"
             value-format="yyyy-MM-dd"
             type="date"
             :editable="false"
             :picker-options="pickerOptions"
             placeholder="请选择日期">
           </el-date-picker>
           <el-date-picker
              v-if="type=='2'"
              v-model="value2"
              value-format="yyyy-MM"
              type="month"
              :picker-options="pickerOptions"
              placeholder="请选择月">
            </el-date-picker>
            <div  v-if="type=='3'">
              <el-date-picker
              style="margin-right: 20px;"
                 v-model="year"
                 type="year"
                 value-format="yyyy"
                 :picker-options="pickerOptions"
                 placeholder="请选择年">
               </el-date-picker>
               <el-radio-group v-model="xqLb">
                 <el-radio :label="1">上</el-radio>
                 <el-radio :label="2">下</el-radio>
               </el-radio-group>
             </div>
        </el-form-item>
        <!-- <el-form-item label="园所名称：" prop="name">
                    <el-select v-model="queryParams.name" clearable filterable placeholder="请选择">
                        <el-option
                          v-for="item in schoolList"
                          :key="item.code"
                          :label="item.title"
                          :value="item.code">
                        </el-option>
                      </el-select>
                    </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
       </el-form>
      <div class="charts">
          <div ref="myChartdom" class="mychartdom"></div>
          <div  ref="chartdom" class="chartdom"></div>
      </div>
  </div>
</template>
<script>
import moment from "moment";
import { selectSemster} from "@/api/base/semster";
import { getdayfood,getcategoryDay,getSemsterfood,getcategoryMonth,getmonthFood,getcategorySemster} from "@/api/qu/qyssyygl";
export default {
name: "yssctj",
data() {
  return {
      radioTimeChange: "日",
      type:'1',
      xqLb:1,
      startDate:'',
      endDate:'',
      timeLable:'日期：',
      value1:new Date(),
      value2:new Date(),
      year:new Date(),
        //学期
      semsterList: [],
      dateTypeOptions:[],
      foodTypeOptions:[],
      schoolList:[],
      open: false,
      // 查询参数
      queryParams: {
        type:'',
        semId:'',
        name:''
      },
      series:[],
      querys:{},
      myCharts:null,
      btchart:null,
      foodList:[
        {name:'幼儿园1',value:250},
        {name:'幼儿园2',value:100},
        {name:'幼儿园3',value:100}
      ],
      categoryList:[],
      categoryX:[],
      legendSelected:{
        '谷类及制品':false,
        '薯类、淀粉及制品':false,
        '干豆类及制品':false,
        '蔬菜类及制品':false,
      },
      legendFlag:[true,false],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
  };
},
created() {
  selectSemster({'status':1}).then(response => {
    this.semsterList = response.rows;
     this.queryParams.semId=this.semsterList[0].title
  });
  this.getDicts("date_type").then(response => {
        this.dateTypeOptions = response.data;
      });
  this.getDicts("food_type").then(response => {
    this.categoryList=[]
    this.foodTypeOptions = response.data;
    this.categoryList=[...this.foodTypeOptions];
  });
},
mounted(){
   this.myCharts = this.$echarts.init(this.$refs.myChartdom);
   this.btchart = this.$echarts.init(this.$refs.chartdom);
   this.getList();
   window.addEventListener("resize", this.monitorResize);
 },
methods: {
 getList(){
    if(this.radioTimeChange=='日'){
      this.getdayfood();
      this.getcategoryDay();
    }else if(this.radioTimeChange=='月'){
        this.getmonthFood();
        this.getcategoryMonth();
    }else if(this.radioTimeChange=='学期'){
        this.getSemsterfood();
        this.getcategorySemster()
    }
  },
  getTime(){
        if(this.xqLb=='1'){
            this.startDate=moment(this.year).format("YYYY")+'-09-01';
            this.endDate= moment(this.year).add(1, "year").format("YYYY")+'-01-31';
        }else{
            this.startDate=moment(this.year).add(1, "year").format("YYYY")+'-02-01';
            this.endDate= moment(this.year).add(1, "year").format("YYYY")+'-08-01';
        }
  },
  // 一天的各园食材总量
  async getdayfood(){
    try {
        const obj ={
          createDate:moment(this.value1).format("YYYY-MM-DD")
        }
         const {data} =  await getdayfood(obj);
         this.foodList=data.map(item=>{
           return {
            name:item.schoolName,
            value:item.quantity
           }
         });
         this.myChartsFn();
    } catch (error) {
      console.log(error);
    }
  },
  //一天的各园食材各类食材数量
  async getcategoryDay(){
    this.categoryList.map((item,index)=>{
       item['category']=[];
    })
    this.categoryX=[];
    try {
        const obj ={
          createDate:moment(this.value1).format("YYYY-MM-DD")
        }
         const {data} =  await getcategoryDay(obj);
         data.map(item=>{
             this.categoryX.push(item.schoolName)
             this.categoryList.map((items,index)=>{
            let indexs=index+1
            items['category'].push(item['category'+indexs]);
          })
         })
         this.get()
    } catch (error) {
      console.log(error);
    }
  },
  get(){
    this.series=[];
    this.categoryList.map(item=>{
      this.series.push(
        {
                  name: item.dictLabel,
                  type: 'bar',
                  barWidth:'80',
                  emphasis: {
                      focus: 'series'
                  },
                  label: {
                    show: true,
                    position: 'inside',
                    fontSize: 15
                  },
                  data: item.category,
              },
      )
    })
    this.btchartsFun();

  },
  //一月的各园食材总量
  async getmonthFood(){
    try {
        const obj ={
          createDate:moment(this.value2).format("YYYY-MM")
        }
         const {data} =  await getmonthFood(obj);
         this.foodList=data.map(item=>{
           return {
            name:item.schoolName,
            value:item.quantity
           }
         });
         this.myChartsFn();
    } catch (error) {
      console.log(error);
    }
  },
  //一月的各园食材各类食材数量
  async getcategoryMonth(){
    this.categoryList.map((item,index)=>{
       item['category']=[];
    })
    this.categoryX=[];
    try {
        const obj ={
          createDate:moment(this.value2).format("YYYY-MM")
        }
         const {data} =  await getcategoryMonth(obj);
         Array.isArray(data)?data.map(item=>{
             this.categoryX.push(item.schoolName)
             this.categoryList.map((items,index)=>{
            let indexs=index+1
            items['category'].push(item['category'+indexs]);
          })
         }):[]
         this.get();
    } catch (error) {
      console.log(error);
    }
  },
    // 学期的各园食材总量
  async getSemsterfood(){
    this.getTime();
    try {
        const obj ={
          startDate:this.startDate,
          endDate:this.endDate,
        }
         const {data} =  await getSemsterfood(obj);
         this.foodList=data.map(item=>{
           return {
            name:item.schoolName,
            value:item.quantity
           }
         });
         this.myChartsFn();
    } catch (error) {
      console.log(error);
    }
  },
    //学期各园食材各类食材数量
  async getcategorySemster(){
    this.categoryList.map((item,index)=>{
       item['category']=[];
    })
    this.categoryX=[];
    try {
        const obj ={
          startDate:this.startDate,
          endDate:this.endDate,
        }
         const {data} =  await getcategorySemster(obj);
         Array.isArray(data)?data.map(item=>{
             this.categoryX.push(item.schoolName)
             this.categoryList.map((items,index)=>{
            let indexs=index+1
            items['category'].push(item['category'+indexs]);
          })
         }):[]
         this.get();
    } catch (error) {
      console.log(error);
    }
  },
     // 材料类型字典翻译
  foodTypeFormat(row, column) {
    return this.selectDictLabel(this.foodTypeOptions, row.materialType);
  },
   //图表日期选择
   changeTab(vId){
      let obj = {};
       obj = this.dateTypeOptions.find((item)=>{  //这里的radioPay就是上面遍历的数据源
           return item.dictLabel === vId;  //筛选出匹配数据，这里的value是你遍历数组每一项的value，如果没有对后台返回的数据做处理，一般为id
       });
      this.type = obj.dictValue  //打印出来的obj.value  就是想要的label值
    if (vId == "学期") {
      this.type = 3;
      this.timeLable='学期：'
    } else if (vId == "月") {
      this.type = 2;
      this.timeLable='日期：'
    } else if(vId == "日") {
      this.type = 1;
      this.timeLable='日期：'
    }
  },
  /** 搜索按钮操作 */
  handleQuery() {
    this.getList();
  },
  /** 重置按钮操作 */
  resetQuery() {
    this.queryParams= {
      pageNum: 1,
      pageSize: 10,
      title: null, //园所名称
      area: null,  //地区
      nature:null, //地区类型
      level: null, //园所等级
      schoolType: null,  //园所性质
    },
    this.radioTimeChange='日';
    this.type = 1;
    this.timeLable='日期：';
    this.value1=new Date();
    this.value2=new Date();
    this.year=new Date();
    this.xqLb=1;
    this.resetForm("queryForm");
    this.handleQuery();
  },
  //食材总量
  myChartsFn(){
    const  option = {
         title: {
           text: '园所食材统计',
          //  subtext: '纯属虚构',
           left: 'left'
         },
         tooltip: {
           trigger: 'item',
           formatter: function (params) {
           return params.name+':'+params.value;
         },
         },
         legend: {
            // selectedMode: 'single',
            left:'30%',

         },
         grid: {
          top:'50%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
       },
         series: [
           {
             name: '',
             type: 'pie',
             radius: '50%',
             center: ['40%', '60%'],
             data:this.foodList,
             emphasis: {
               itemStyle: {
                 shadowBlur: 10,
                 shadowOffsetX: 0,
                 shadowColor: 'rgba(0, 0, 0, 0.5)'
               }
             }
           }
           ]
        };
        this.myCharts.setOption(option);
        window.addEventListener("resize", this.monitorResize);
  },
  //不同食材数量
  btchartsFun(){
          const option = {
         // backgroud:'#333',
         title: {
           text: '各类食材统计',
          //  subtext: '纯属虚构',
           left: 'left'
         },
         tooltip: {
              trigger: 'axis',
              axisPointer: {
              type: 'shadow'
              }
          },
          legend: {
            selectedMode: 'single',
            left:'30%',

          },
          grid: {
              top:'30%',
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
          },
          xAxis: [
              {
              type: 'category',
              axisLabel: {//x轴文字的配置
               show: true,
               interval: 0,//使x轴文字显示全
              },
              data: this.categoryX
              }
          ],
          yAxis: [
              {
              type: 'value'
              }
          ],
          color:['#2f89cf','#27d08a'],
          series: this.series
          }
            // 使用刚指定的配置项和数据显示图表
            this.btchart.setOption(option,true);
            window.addEventListener("resize", this.monitorResize);
      },
    //地图监听窗口缩放事件
  monitorResize(){
    this.myCharts.resize();
    this.btchart.resize()
  },
}
};
</script>
<style lang="scss" scoped>
.charts{
  display: flex;
  justify-content: space-between;
  width: 100%;
  height:800px;
  .mychartdom{
      width: 40%;
      height: 70%;
      margin-top: 50px;
  }
  .chartdom{
      width: 55%;
      height: 70%;
      margin-top: 50px;
  }
}
</style>
